//
//  BSoftLogService.m
//  BSoftWorkLog
//
//  Created by zarra on 2017/8/3.
//  Copyright © 2017年 zarra. All rights reserved.
//

#import "BSoftLogService.h"
#import "MBProgressHUD+WJ.h"
#define CustomErrorDomain @"cn.net.xyan"
#import "Config.h"
#import "ClientDao.h"

NSString* CmdServletURL = @"http://webmis.bsoft.com.cn:8081/CmdServlet";
NSString* CommandServiceServletURL = @"http://webmis.bsoft.com.cn:8081/servlet/CommandServiceServlet";
NSString* DealDataServletURL = @"http://webmis.bsoft.com.cn:8081/DealDataServlet";
NSString* SaveLogInfoURL = @"http://webmis.bsoft.com.cn:8081/Programs/LogManager/logDetailAction_saveLogInfo.action";

NSString* KeyUserName = @"Username";
NSString* KeyPassword = @"Password";

@interface BSoftLogService ()

@property (nonatomic) NSURLSessionConfiguration *configuration;
@property (nonatomic) AFURLSessionManager *manager;

@property (assign,nonatomic) NSStringEncoding encUTF_8;
@property (assign,nonatomic) NSStringEncoding encGBK;

@property (assign,nonatomic) NSStringEncoding requestEncoding;
@property (assign,nonatomic) NSStringEncoding responseEncoding;

-(NSError*) makeErrorWithCode:(NSInteger)code message:(NSString*) msg;

@end

@implementation BSoftLogService

+ (id)shareInstance {
    static BSoftLogService *service = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service = [[self alloc] init];
    });
    return service;
}

- (id)init {
    if (self = [super init]) {
        self.configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:self.configuration];
        
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        self.encUTF_8 = NSUTF8StringEncoding;
        self.encGBK = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        self.requestEncoding = self.encUTF_8;
        self.responseEncoding = self.encUTF_8;
        
        self.project = [[BSoftProject alloc]init];
        
    }
    return self;
}

- (void)dealloc {
    // Should never be called, but just here for clarity really.
}

-(NSError*) makeErrorWithCode:(NSInteger)code message:(NSString*) msg{
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:msg forKey:NSLocalizedDescriptionKey];
    NSError *error = [NSError errorWithDomain:CustomErrorDomain code:code userInfo:userInfo];
    return error;
}

-(id)getVarForKey:(NSString*)key{
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
-(void)putVar:(id)value forKey:(NSString*)key{
    
    NSDateFormatter* dateFormatter =[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
    
    if (value == nil || value == [NSNull null]) {
        [userDefault removeObjectForKey:key];
    }
    
    else if ([value isKindOfClass:[NSNumber class]]) {
        NSNumber* number = (NSNumber*)value;
        double doubleValue = [number doubleValue];
        [userDefault setDouble:doubleValue forKey:key];
    }
    else if ([value isKindOfClass:[NSDate class]]) {
        NSDate* date = (NSDate*)value;
        NSString *dateString = [dateFormatter stringFromDate:date];
        
        [userDefault setObject:dateString forKey:key];
        
    }
    else if ([value isKindOfClass:[NSString class]]) {
        [userDefault setObject:value forKey:key];
    }
    
    [userDefault synchronize];
    
}

-(BOOL)isUserNameAndPasswordOK{
    NSString* userName = [self getVarForKey:KeyUserName];
    NSString* password = [self getVarForKey:KeyPassword];
    
    if (userName != nil && userName != [NSNull null] && password != nil && password != [NSNull null] ) {
        return YES;
    }
    return NO;
}

-(void)postData:(NSURL*)url data:(NSData*)postBody completionHandler:(void(^)(NSURLResponse * response , id responseObject, NSError * error)) handler{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    unsigned long long postLength = postBody.length;
    NSString *contentLength = [NSString stringWithFormat:@"%llu", postLength];
    [request addValue:contentLength forHTTPHeaderField:@"Content-Length"];
    [request addValue:@"text/xml;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postBody];
    
    NSURLSessionDataTask *dataTask = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (handler) {
            handler(response,responseObject,error);
        }
    }];
    
    [dataTask resume];
}

-(void)postData:(NSURL*)url xmlData:(NSString*)xml completionHandler:(void(^)(NSURLResponse * response , NSString* responseObject, NSError * error)) handler{
    NSData* postBody = [xml dataUsingEncoding:self.requestEncoding];
    [self postData:url data:postBody completionHandler:^(NSURLResponse *response,  id responseObj, NSError *error) {
        if (handler) {
            NSString *xml = nil;
            if (error == nil) {
                [MBProgressHUD showSuccess:@"提交成功！"];
                if(responseObj!=nil && [responseObj isKindOfClass:[NSData class]]){
                    xml = [[NSString alloc] initWithData:responseObj  encoding:self.responseEncoding];
                    
                }else{
                    error  = [[BSoftLogService shareInstance] makeErrorWithCode:ErrResponse message:@"收到的数据格式错误"];
                }
                
            }
            
            handler(response,xml,error);
        }
    }];
}

-(void)userLogin:(NSString*)username password:(NSString*)password completionHandler:(void(^)(NSError* error))handler{
    
    [self putVar:username forKey:KeyUserName];
    [self putVar:password forKey:KeyPassword];
    
    NSString* md5 = [password MD5];
    NSURL* cmdServlet = [NSURL URLWithString:CmdServletURL];
    NSString* postBody = [NSString stringWithFormat:@"<report action=\"logon\" userid=\"%@\" password=\"%@\" licenseCode=\"1501737932051bsoftWeb3\" validation=\"false\" sVerifyCode=\"\" bCheckMust=\"true\"></report>",username,md5 ];
    // NSData *data = [postBody dataUsingEncoding:NSUTF8StringEncoding];
    
    [self postData:cmdServlet xmlData:postBody completionHandler:^(NSURLResponse *response, NSString* responseObject, NSError *error) {
        
        if (handler) {
            if (error == nil) {
                NSDictionary* dict = [NSDictionary dictionaryWithXMLString:responseObject];
                NSString* returnValue = [dict valueForKey:@"_returnvalue"];
                NSString* failureCause = [dict valueForKey:@"_failureCause"];
                NSString* sessionId = [dict valueForKey:@"_sessionid"];
                NSLog(@"get sessionID:%@",sessionId);
                if ([returnValue isEqualToString:@"false"]) {
                    
                    error = [[BSoftLogService shareInstance]makeErrorWithCode:ErrLogin message:failureCause];
                    
                }else{
                    NSLog(@"Login success");
                    kSAVE_VALUE(username, kUserName);
                    [ClientDao setPassWord:password];
                    [[BSoftLogService shareInstance]setSessionID:sessionId];
                }
                
            }
            
            handler(error);
        }
    }];
    
}
-(void)queryLastProject:(NSString*)username completionHandler:(void(^)(NSDictionary* dict,NSError* error))handler{
    NSString* template =  @"<report pagesize=\"1\" action=\"show\" pageno=\"1\" condition=\"WGBZ=0\">\n"
    @"\t<Titles name=\"(SELECT * FROM (SELECT P.PROJECTID,P.PROJECTNAME,P.AREA,P.FLAG,P.WGBZ FROM KQ_GZRZ K LEFT OUTER JOIN T_PROJECT P ON K.GSXM=P.PROJECTID WHERE K.GSXM IS NOT NULL AND K.KQID IN (SELECT ID FROM T_KQB WHERE YGGH='%@') ORDER BY K.ID DESC) WHERE 1&gt;=ROWNUM) T\">\n"
    @"\t\t<Title name=\"PROJECTID\" alias=\"项目ID\"/>\n"
    @"\t\t<Title name=\"PROJECTNAME\" alias=\"项目名称\"/>\n"
    @"\t\t<Title name=\"AREA\" alias=\"归属部门\"/>\n"
    @"\t\t<Title name=\"FLAG\" alias=\"归属类别\"/>\n"
    @"\t</Titles>\n"
    @"</report>";
    
    NSString* req = [NSString stringWithFormat:template,username];
    
    NSURL* dealDataServlet = [NSURL URLWithString:DealDataServletURL];
    
    [[BSoftLogService shareInstance]postData:dealDataServlet xmlData:req completionHandler:^(NSURLResponse *response, NSString *responseObject, NSError *error) {
        if (handler) {
            NSDictionary* dict = nil;
            if (error == nil) {
                dict = [NSDictionary dictionaryWithXMLString:responseObject];
                NSDictionary* result = [dict valueForKey:@"Result"];
                NSDictionary* R = [result valueForKey:@"R"];
                NSArray* C = [R valueForKey:@"C"];
                
                [[[BSoftLogService shareInstance]project] setProjectID:[C objectAtIndex:0]];
                [[[BSoftLogService shareInstance]project] setProjectName:[C objectAtIndex:1]];
                [[[BSoftLogService shareInstance]project] setArea:[C objectAtIndex:2]];
                [[[BSoftLogService shareInstance]project] setFlag:[C objectAtIndex:3]];
            }
            handler(dict,error);
        }
    }];
}

-(void)getTodayLog:(NSString*)username completionHandler:(void(^)(NSString* rsp,NSError* error))handler{
    NSString* tmpl = @"<Request><Head action=\"getLog\" sessionId=\"%@\"/><Body><Subject userId=\"%@\" id=\"\"/></Body></Request>";
    NSString* req = [NSString stringWithFormat:tmpl,self.sessionID,[self getVarForKey:KeyUserName]];
    NSURL* commandServiceServlet = [NSURL URLWithString:CommandServiceServletURL];
    
    [[BSoftLogService shareInstance]postData:commandServiceServlet xmlData:req completionHandler:^(NSURLResponse *response, NSString *responseObject, NSError *error) {
        if (handler) {
            NSString* text = nil;
            if (error == nil) {
                NSLog(@"response:%@",responseObject);
                NSDictionary* dict = [NSDictionary dictionaryWithXMLString:responseObject];
                
                NSDictionary* body = [dict valueForKey:@"Body"];
                NSDictionary* head = [dict valueForKey:@"Head"];
                
                NSDictionary* subject = [body valueForKey:@"Subject"];
                text = [subject valueForKey:@"__text"];
                NSString* msID = [head valueForKey:@"_msId"];
                
                [[BSoftLogService shareInstance]setMsID:msID];
            }
            handler(text,error);
        }
    }];
    
}

-(void)saveWorkLog:(BSoftWorkLog*)workLog completionHandler:(void(^)(NSDictionary* dict,NSError* error))handler{
    //     NSString* tmpl = @"<Request><Head action=\"saveLog\" sessionId=\"%@\" userId=\"%@\" msId=\"%@\" id="" totalNum=\"%@\" count=\"1\" projectName=\"%@\"/><Body><Subject>%@</Subject><xm>%@</xm><lb>14</lb><xmbm>%@</xmbm><gzsj>%@</gzsj><rzqk>%@</rzqk><ccbz>%@</ccbz><gzzpf>%@</gzzpf></Body></Request>";
    
    NSString* tmpl = @"<Request><Head action=\"saveLog\" sessionId=\"{{sessionId}}\" userId=\"{{username}}\" msId=\"{{msId}}\" id=\"\" totalNum=\"{{totalNum}}\" count=\"1\" projectName=\"{{projectName}}\"/><Body><Subject>{{content}}</Subject><xm>{{projectID}}</xm><lb>14</lb><xmbm>{{area}}</xmbm><gzsj>{{totalNum}}</gzsj><rzqk>{{rzqk}}</rzqk><ccbz>{{ccbz}}</ccbz><gzzpf>{{gzzpf}}</gzzpf></Body></Request>";
    
    NSDictionary* params = @{@"sessionId":self.sessionID
                             ,@"username":workLog.username
                             ,@"msId":self.msID
                             ,@"totalNum":workLog.totalNum
                             ,@"projectName":self.project.projectName
                             ,@"content":workLog.content
                             ,@"projectID":self.project.projectID
                             ,@"area":self.project.area
                             ,@"rzqk":workLog.rzqk
                             ,@"ccbz":workLog.ccbz
                             ,@"gzzpf":workLog.score};
    //    NSString* req = [NSString stringWithFormat:tmpl
    //                     ,self.sessionID,workLog.username,self.msID,workLog.totalNum,self.project.projectName,workLog.content
    //                     ,self.project.projectID,self.project.area,workLog.totalNum, workLog.rzqk,workLog.ccbz,  workLog.score];
    
    NSString *req = [GRMustacheTemplate renderObject:params fromString:tmpl error:NULL];
    
    NSLog(@"req:%@",req);
    
    NSURL* saveLogInfo = [NSURL URLWithString:SaveLogInfoURL];
    
    [[BSoftLogService shareInstance]postData:saveLogInfo xmlData:req completionHandler:^(NSURLResponse *response, NSString *responseObject, NSError *error) {
        if (handler) {
            //NSString* text = nil;
            NSDictionary* dict = nil;
            if (error == nil) {
                NSLog(@"response:%@",responseObject);
                [MBProgressHUD showSuccess:@"提交成功！"];
                dict = [NSDictionary dictionaryWithXMLString:responseObject];
                
                //                NSDictionary* body = [dict valueForKey:@"Body"];
                //                NSDictionary* head = [dict valueForKey:@"Head"];
                //
                //                NSDictionary* subject = [body valueForKey:@"Subject"];
                //                text = [subject valueForKey:@"__text"];
                //                NSString* msID = [head valueForKey:@"_msId"];
                //
                //                [[BSoftLogService shareInstance]setMsID:msID];
            }else{
               [MBProgressHUD showError:@"提交失败，请登陆网页"];
            }
            handler(nil,error);
        }
    }];
    
    
}

@end
